package com.shaozi.nc.quartz.job;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.shaozi.common.schedule.DyncQuartzManage;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.OrgPushMsgModel;
import com.shaozi.nc.data.mongodao.OrgPushMsgMDao;
import com.shaozi.nc.io.mq.OrgPushMsgProducer;
import com.shaozi.utils.common.BeanUtils;
import com.shaozi.utils.common.SysUtils;

/**
 * 跟组织结构有关的信息推送任务<br>
 * 比如：写工作汇报提醒，公司设置跟部门设置可能会重合
 * 
 * @author brenx
 * 
 */
public class OrgPushJob implements Job {
	private final Logger logger = Logger.getLogger(OrgPushJob.class);

	@Autowired
	private OrgPushMsgProducer orgPushMsgProducer;

	public OrgPushJob() {

	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		TriggerKey key = context.getTrigger().getKey();
		String groupId = key.getGroup();

		if (StringUtils.isEmpty(groupId)) {
			logger.warn("get trigger's group null");
			return;
		}
		String compId = groupId.split("_")[0];
		String _id = key.getName();
		if (StringUtils.isEmpty(_id)) {
			logger.warn("get trigger's name null," + compId);
			return;
		}
		OrgPushMsgMDao dao = (OrgPushMsgMDao) BeanUtils.getBean("orgPushMsgMDao");
		OrgPushMsgModel model = dao.getById(compId, _id);
		if (model == null) {
			logger.info("get id null: " + _id);
			removeJob(context);
			return;
		}
		doPush(model);
		if (logger.isInfoEnabled()) {
			logger.info(
					"job=" + _id + ",next fire time:" + SysUtils.formatDate(context.getTrigger().getNextFireTime()));
		}
	}

	private void doPush(OrgPushMsgModel model) {
		// TODO 需要判断公司，部门的类型
		orgPushMsgProducer.pushMsg(model);
	}

	private void removeJob(JobExecutionContext context) {
		DyncQuartzManage mgr = (DyncQuartzManage) BeanUtils.getBean("dyncQuartzMgr");
		JobKey jobKey = context.getJobDetail().getKey();
		TriggerKey key = context.getTrigger().getKey();
		try {
			mgr.removeJob(jobKey, key);
		} catch (SchedulerException e) {
			logger.error(SzException.getStackMessage(e));
		}

	}

}
